package XMLCreator;

import java.util.Collection;
import java.util.Iterator;
import java.util.Vector;

import javax.xml.stream.XMLStreamException;

import DataObjects.Article;
import DataObjects.Topic;
import DisplayDatas.*;
import Main.*;

public class XMLCreatorListOfArticles<A extends ListOfArticlesToDisplay> extends XMLCreator<A>{

	protected void buildXMLInner(A item)
			throws XMLStreamException {
		Iterator<Article> iterator1=item.getArticlesIterator();
		
		while (iterator1.hasNext()){
			Article article=iterator1.next();
//			System.out.println("XMLCreatorListOfArticles.buildXMLInner in while title="+article.getTitle());//TODO
			startNode("article");
			createDetail("id",article.getId()+"");
			createDetail("title",article.getTitle());
			for(Pair<String,Object> detail : article.getMetadata()){
				createDetail(detail.getFirst(),detail.getSecend());
			}
			createDetail("summary",article.getSummary());
			createDetail("topicsID",allTopicID(article.getTopics()));
			createDetail("topicsName",allTopicName(article.getTopics()));
			finishNode("article");
		}	
		
		Vector<Pair<String, Integer>> allCats=item.getCats();
		
		System.out.println("XMLCreatorListOfArticles.buildXMLInner "+allCats);//TODO
		
		for(Pair<String,Integer> cat : allCats){
			//TopicToDisplay topic=iterator4.next();
			startNode("relateCat");
			createDetail("name",cat.getFirst());
			createDetail("countFound",cat.getSecend()+"");
			finishNode("relateCat");
		}
		
		startNode("general");
		createDetail("countArticles",item.getCountFound()+"");
		finishNode("general");
	}
	
	private String allTopicID(Collection<Topic> topics){
		String ans="";
		boolean doOneLoop=false;
		for (Topic topic : topics){
			ans+=topic.getId()+",";
			doOneLoop=true;
		}
		if (doOneLoop)
			return ans.substring(0,ans.length()-1);
		else
			return "";
	}
	
	private String allTopicName(Collection<Topic> topics){
		String ans="";
		boolean doOneLoop=false;
		for (Topic topic : topics){
			ans+=topic.getName()+",";
			doOneLoop=true;
		}
		if (doOneLoop)
			return ans.substring(0,ans.length()-1);
		else
			return "";
	}
}
